package com.danny;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIODemo {
	public static void main(String[] args) {
		readNIO();
	}

	private static void readNIO() {
		FileInputStream fileInputStream = null;
		FileChannel channel = null;
		int capacity = 2000;
		int length = -1;
		try {
			File file = new File("E:\\NIO.txt");
			if (!file.exists()){
				file.createNewFile();
			}
			fileInputStream = new FileInputStream(file);
			channel = fileInputStream.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
			while ((length = channel.read(byteBuffer)) != -1) {
				byteBuffer.clear();
				byte[] bytes = byteBuffer.array();
				String str = new String(bytes, 0, length);
				System.out.println(str);
			}
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (channel != null) {
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fileInputStream != null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
